<template>
  <div class="system-management">
    <div class="page-header">
      <h1>系统管理</h1>
      <p>管理系统配置和设置</p>
    </div>

    <div class="management-grid">
      <!-- 系统配置 -->
      <div class="management-card">
        <div class="card-header">
          <h3>系统配置</h3>
        </div>
        <div class="card-content">
          <div class="config-item">
            <label>系统名称</label>
            <input v-model="systemConfig.name" type="text" />
          </div>
          <div class="config-item">
            <label>系统版本</label>
            <input v-model="systemConfig.version" type="text" readonly />
          </div>
          <div class="config-item">
            <label>维护模式</label>
            <label class="switch">
              <input v-model="systemConfig.maintenanceMode" type="checkbox" />
              <span class="slider"></span>
            </label>
          </div>
        </div>
      </div>

      <!-- 数据库管理 -->
      <div class="management-card">
        <div class="card-header">
          <h3>数据库管理</h3>
        </div>
        <div class="card-content">
          <div class="db-stats">
            <div class="stat-item">
              <span class="label">数据库大小</span>
              <span class="value">{{ dbStats.size }}</span>
            </div>
            <div class="stat-item">
              <span class="label">表数量</span>
              <span class="value">{{ dbStats.tables }}</span>
            </div>
            <div class="stat-item">
              <span class="label">记录总数</span>
              <span class="value">{{ dbStats.records }}</span>
            </div>
          </div>
          <div class="db-actions">
            <button @click="backupDatabase" class="btn btn-primary">备份数据库</button>
            <button @click="optimizeDatabase" class="btn btn-secondary">优化数据库</button>
          </div>
        </div>
      </div>

      <!-- 课程管理 -->
      <div class="management-card">
        <div class="card-header">
          <h3>课程管理</h3>
        </div>
        <div class="card-content">
          <div class="course-stats">
            <div class="stat-item">
              <span class="label">总课程数</span>
              <span class="value">{{ courseStats.total }}</span>
            </div>
            <div class="stat-item">
              <span class="label">活跃课程</span>
              <span class="value">{{ courseStats.active }}</span>
            </div>
            <div class="stat-item">
              <span class="label">已分配教师</span>
              <span class="value">{{ courseStats.assigned }}</span>
            </div>
          </div>
          <div class="course-actions">
            <button @click="showCourseModal = true" class="btn btn-primary">创建课程</button>
            <button @click="loadCourses" class="btn btn-secondary">刷新列表</button>
          </div>
          <div class="course-list" v-if="courses.length > 0">
            <div v-for="course in courses.slice(0, 5)" :key="course.id" class="course-item">
              <div class="course-info">
                <span class="course-name">{{ course.name }}</span>
                <span class="course-code">{{ course.course_code }}</span>
              </div>
              <div class="course-actions-mini">
                <button @click="editCourse(course)" class="btn-mini">编辑</button>
                <button @click="deleteCourse(course)" class="btn-mini btn-danger">删除</button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 日志管理 -->
      <div class="management-card">
        <div class="card-header">
          <h3>系统日志</h3>
        </div>
        <div class="card-content">
          <div class="log-filters">
            <select v-model="logFilter.level">
              <option value="">所有级别</option>
              <option value="error">错误</option>
              <option value="warning">警告</option>
              <option value="info">信息</option>
            </select>
            <input v-model="logFilter.date" type="date" />
          </div>
          <div class="log-list">
            <div v-for="log in filteredLogs" :key="log.id" class="log-item" :class="log.level">
              <span class="timestamp">{{ log.timestamp }}</span>
              <span class="level">{{ log.level }}</span>
              <span class="message">{{ log.message }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 课程创建/编辑模态框 -->
    <div v-if="showCourseModal" class="modal-overlay" @click="showCourseModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ currentCourse ? '编辑课程' : '创建课程' }}</h3>
          <button @click="showCourseModal = false" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>课程代码</label>
            <input v-model="courseForm.course_code" type="text" placeholder="请输入课程代码" />
          </div>
          <div class="form-group">
            <label>课程名称</label>
            <input v-model="courseForm.name" type="text" placeholder="请输入课程名称" />
          </div>
          <div class="form-group">
            <label>课程描述</label>
            <textarea v-model="courseForm.description" placeholder="请输入课程描述"></textarea>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label>学分</label>
              <input v-model.number="courseForm.credits" type="number" min="1" max="10" />
            </div>
            <div class="form-group">
              <label>课程类型</label>
              <select v-model="courseForm.category">
                <option value="required">必修</option>
                <option value="elective">选修</option>
                <option value="core">核心</option>
              </select>
            </div>
          </div>
          <div class="form-row">
            <div class="form-group">
              <label>学期</label>
              <input v-model="courseForm.semester" type="text" placeholder="如：2024春" />
            </div>
            <div class="form-group">
              <label>学时</label>
              <input v-model.number="courseForm.hours" type="number" min="0" />
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showCourseModal = false" class="btn btn-secondary">取消</button>
          <button @click="saveCourse" class="btn btn-primary" :disabled="loading">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { getAllCourses, createCourse, updateCourse, deleteCourse } from '@/api/course-management/courses'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'SystemManagement',
  setup() {
    const systemConfig = ref({
      name: '在线考试系统',
      version: '1.0.0',
      maintenanceMode: false
    })

    const dbStats = ref({
      size: '125.6 MB',
      tables: 15,
      records: 12580
    })

    const logFilter = ref({
      level: '',
      date: ''
    })

    const logs = ref([
      { id: 1, timestamp: '2024-01-15 10:30:25', level: 'info', message: '用户登录成功' },
      { id: 2, timestamp: '2024-01-15 10:25:12', level: 'warning', message: '数据库连接超时' },
      { id: 3, timestamp: '2024-01-15 10:20:08', level: 'error', message: '文件上传失败' }
    ])

    // 课程管理相关
    const courses = ref([])
    const courseStats = ref({
      total: 0,
      active: 0,
      assigned: 0
    })
    const showCourseModal = ref(false)
    const currentCourse = ref(null)
    const courseForm = ref({
      course_code: '',
      name: '',
      description: '',
      credits: 1,
      category: 'required',
      semester: '',
      hours: 0
    })
    const loading = ref(false)

    const filteredLogs = computed(() => {
      return logs.value.filter(log => {
        if (logFilter.value.level && log.level !== logFilter.value.level) return false
        if (logFilter.value.date && !log.timestamp.includes(logFilter.value.date)) return false
        return true
      })
    })

    const backupDatabase = () => {
      alert('数据库备份功能开发中...')
    }

    const optimizeDatabase = () => {
      alert('数据库优化功能开发中...')
    }

    // 课程管理方法
    const loadCourses = async () => {
      try {
        loading.value = true
        const response = await getAllCourses()
        if (response.data && response.data.success) {
          courses.value = response.data.data || []
          updateCourseStats()
        }
      } catch (error) {
        console.error('加载课程列表失败:', error)
        ElMessage.error('加载课程列表失败')
      } finally {
        loading.value = false
      }
    }

    const updateCourseStats = () => {
      courseStats.value.total = courses.value.length
      courseStats.value.active = courses.value.filter(c => c.status === 'active').length
      courseStats.value.assigned = courses.value.filter(c => c.teachers && c.teachers.length > 0).length
    }

    const editCourse = (course) => {
      currentCourse.value = course
      Object.assign(courseForm.value, {
        course_code: course.course_code,
        name: course.name,
        description: course.description,
        credits: course.credits,
        category: course.category,
        semester: course.semester,
        hours: course.hours
      })
      showCourseModal.value = true
    }

    const saveCourse = async () => {
      try {
        loading.value = true
        let response
        
        if (currentCourse.value) {
          // 编辑课程
          response = await updateCourse(currentCourse.value.id, courseForm.value)
        } else {
          // 创建课程
          response = await createCourse(courseForm.value)
        }
        
        if (response.data && response.data.success) {
          ElMessage.success(currentCourse.value ? '更新成功' : '创建成功')
          showCourseModal.value = false
          resetCourseForm()
          loadCourses()
        }
      } catch (error) {
        console.error('保存课程失败:', error)
        ElMessage.error('保存课程失败')
      } finally {
        loading.value = false
      }
    }

    const resetCourseForm = () => {
      currentCourse.value = null
      Object.assign(courseForm.value, {
        course_code: '',
        name: '',
        description: '',
        credits: 1,
        category: 'required',
        semester: '',
        hours: 0
      })
    }

    const removeCourse = async (course) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除课程 ${course.name} 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        loading.value = true
        const response = await deleteCourse(course.id)
        if (response.data && response.data.success) {
          ElMessage.success('删除成功')
          loadCourses()
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除课程失败:', error)
          ElMessage.error('删除课程失败')
        }
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      // 加载系统配置
      loadCourses()
    })

    return {
      systemConfig,
      dbStats,
      logFilter,
      logs,
      filteredLogs,
      backupDatabase,
      optimizeDatabase,
      // 课程管理
      courses,
      courseStats,
      showCourseModal,
      currentCourse,
      courseForm,
      loading,
      loadCourses,
      editCourse,
      saveCourse,
      resetCourseForm,
      deleteCourse: removeCourse
    }
  }
}
</script>

<style scoped>
/* 课程管理样式 */
.course-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.course-actions {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.course-list {
  max-height: 200px;
  overflow-y: auto;
}

.course-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 8px;
  background: #f9f9f9;
}

.course-info {
  display: flex;
  flex-direction: column;
}

.course-name {
  font-weight: bold;
  color: #333;
}

.course-code {
  font-size: 12px;
  color: #666;
}

.course-actions-mini {
  display: flex;
  gap: 5px;
}

.btn-mini {
  padding: 4px 8px;
  font-size: 12px;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  background: #007bff;
  color: white;
}

.btn-mini:hover {
  background: #0056b3;
}

.btn-mini.btn-danger {
  background: #dc3545;
}

.btn-mini.btn-danger:hover {
  background: #c82333;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90vw;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 15px;
}

.form-row {
  display: flex;
  gap: 15px;
}

.form-row .form-group {
  flex: 1;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
  color: #333;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group textarea {
  height: 80px;
  resize: vertical;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #e0e0e0;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-primary:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background: #545b62;
}
.system-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
}

.management-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.management-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  overflow: hidden;
}

.card-header {
  background: #f8f9fa;
  padding: 15px 20px;
  border-bottom: 1px solid #e9ecef;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.card-content {
  padding: 20px;
}

.config-item {
  margin-bottom: 15px;
}

.config-item label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.config-item input[type="text"] {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input {
  opacity: 0;
  width: 0;
  height: 0;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 34px;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  transition: .4s;
  border-radius: 50%;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:checked + .slider:before {
  transform: translateX(26px);
}

.db-stats {
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.stat-item .label {
  font-weight: 500;
}

.stat-item .value {
  color: #007bff;
  font-weight: bold;
}

.db-actions {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.log-filters {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.log-filters select,
.log-filters input {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.log-list {
  max-height: 300px;
  overflow-y: auto;
}

.log-item {
  display: flex;
  gap: 10px;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
  font-size: 14px;
}

.log-item.error {
  color: #dc3545;
}

.log-item.warning {
  color: #ffc107;
}

.log-item.info {
  color: #17a2b8;
}

.timestamp {
  min-width: 120px;
  color: #666;
}

.level {
  min-width: 60px;
  font-weight: bold;
  text-transform: uppercase;
}

.message {
  flex: 1;
}
</style>